package com.lvw.weather.forcast.web;

import com.lvw.weather.dto.Weather;
import com.lvw.weather.forcast.component.SinkSender;
import com.lvw.weather.forcast.serviec.ForcastService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpRequest;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@RefreshScope
@RestController
public class ForcastController implements IForcastAPI {

    //final Logger log = Logger.getLogger(getClass().toString());
    final Logger logger = LoggerFactory.getLogger(ForcastController.class);

    @Autowired
    ForcastService forcastService;

    @Value("${weather.title:Weather App}")
    String appTitle;

    @Autowired
    SinkSender sinkSender;

    @Autowired
    HttpServletRequest request;

    @Override
    public String forcast(String city) {

        int sleeptime = new Random().nextInt(3000);

        /*// 模拟处理耗时
        log.info("Thread sleep: " + sleeptime);
        try {
            Thread.sleep(sleeptime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/

        int i = new Random().nextInt(100);

        String s = "Receive request: " + request.getRequestURI();
        logger.info("===> SinkSender send: {}" , s);

        sinkSender.output().send(MessageBuilder.withPayload(s).build());

        return appTitle + " say: Toady Sunny-" + i;

    }

    @Override
    public List<String> forcasts(List<String> citys) {
        return citys.stream().map(s -> "sunny-" + new Random().nextInt(100)).collect(Collectors.toList());
    }

    @Override
    public boolean updateForcast(String city, Weather weather) {

        return forcastService.updateForcast(city, weather);
    }
}
